<template>
  <div class="all-profit-statistics">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <div class="header-title">
            <i class="el-icon-pie-chart"></i>
            <span>全量收益统计总览</span>
            <small class="summary-info">共 {{ filteredStockList.length }} 只股票</small>
            <el-checkbox 
              v-model="showCurrentOnly" 
              style="margin-left: 15px;"
              @change="handleFilterChange"
            >
              只查看当前持仓
            </el-checkbox>
          </div>
        </div>
      </template>

      <div v-if="loading" class="loading">
        <el-skeleton :rows="3" animated />
      </div>

      <div v-else-if="allDataLoaded" class="statistics-content">
        <!-- 整体收益汇总 -->
        <div class="overall-summary">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="summary-card highlight">
                <div class="summary-title">总收益</div>
                <div class="summary-value" :class="getProfitClass(totalProfit)">
                  ¥{{ formatNumber(totalProfit) }}
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="summary-card">
                <div class="summary-title">总做T收益</div>
                <div class="summary-value" :class="getProfitClass(totalTProfit)">
                  ¥{{ formatNumber(totalTProfit) }}
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="summary-card">
                <div class="summary-title">做T收益占比</div>
                <div class="summary-value" :class="getProfitClass(parseFloat((Math.abs(totalTProfit) / Math.abs(totalProfit)) * 100).toFixed(1))">
                  {{ parseFloat((Math.abs(totalTProfit) / Math.abs(totalProfit)) * 100).toFixed(1) }} %
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="summary-card">
                <div class="summary-title">平均收益率</div>
                <div class="summary-value" :class="getProfitClass(averageReturnRate)">
                  {{ formatNumber(averageReturnRate) }}%
                </div>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 股票收益饼状图 - 紧凑布局 -->
        <div class="profit-composition compact">
          <h4 class="section-title compact-title">股票收益分布</h4>
          <div v-if="hasChartData" class="echarts-container compact-chart" ref="pieChart"></div>
          <div v-else class="no-chart-data compact-empty">
            <el-empty 
              description="暂无收益数据" 
              :image-size="80"
            />
          </div>
        </div>

        <!-- 详细统计表格 - 带分页和排序 -->
        <div class="detailed-table">
          <h4 class="section-title">详细统计</h4>
          <el-table
            :data="pagedTableData"
            style="width: 100%"
            size="small"
            :max-height="350"
            stripe
            @sort-change="handleSortChange"
          >
            <el-table-column 
              prop="stockName" 
              label="股票名称" 
              min-width="85"
              align="center"
              sortable="custom"
            />
            <el-table-column 
              prop="currentPrice" 
              label="当前价" 
              min-width="60"
              align="center"
            />
            <el-table-column 
              prop="breakEvenPrice" 
              label="保本价" 
              min-width="60"
              align="center"
            />
            <el-table-column 
              prop="diff" 
              label="差点" 
              min-width="60"
              align="center"
              sortable="custom"
            >
            <template #default="{ row }">
                <span :class="getProfitClass(row.diff)">
                  {{ row.diff }}
                </span>
              </template>
             </el-table-column>
            <el-table-column 
              prop="profitLoss" 
              label="总盈亏" 
              min-width="60"
              align="center"
              sortable="custom"
            >
              <template #default="{ row }">
                <span :class="getProfitClass(row.profitLoss)">
                  ¥{{ formatNumber(row.profitLoss) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column 
              prop="tProfit" 
              label="做T收益" 
              min-width="60"
              align="center"
              sortable="custom"
            >
              <template #default="{ row }">
                <span :class="getProfitClass(row.tProfit)">
                  ¥{{ formatNumber(row.tProfit) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column 
              prop="returnRate" 
              label="收益率" 
              min-width="60"
              align="center"
              sortable="custom"
            >
              <template #default="{ row }">
                <span :class="getProfitClass(row.returnRate)">
                  {{ formatNumber(row.returnRate) }}%
                </span>
              </template>
            </el-table-column>

            <el-table-column 
              prop="tProfitRatio" 
              label="做T收益占比" 
              min-width="90"
              align="center"
              sortable="custom"
            >
              <template #default="{ row }">
                <span :class="getProfitClass(row.tProfitRatio)">
                  {{ formatNumber(row.tProfitRatio) }}%
                </span>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页组件 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              :page-size="pageSize"
              :total="sortedData.length"
              layout="total, prev, pager, next, jumper"
              size="small"
              @current-change="handlePageChange"
            />
          </div>
        </div>
      </div>

      <div v-else class="empty">
        <el-empty 
          description="暂无股票数据" 
          :image-size="100"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getStockList, getCurrentStocks } from '@/api/stockTrading'
import { getStockLatestData } from '@/api/stockStatistics'
import { getTotalTProfitByStockCode } from '@/api/stockTTransaction';

export default {
  name: 'AllProfitStatistics',
  data() {
    return {
      stockList: [],
      allStockData: [],
      loading: false,
      chart: null,
      currentStocks: [],
      // 汇总数据
      totalProfit: 0,
      totalTProfit: 0,
      averageReturnRate: 0,
      
      // 分页相关
      currentPage: 1,
      pageSize: 10,
      
      // 排序相关
      sortColumn: '',
      sortOrder: '',
      
      allDataLoaded: false,
      showCurrentOnly: false
    }
  },
  computed: {
    // 过滤后的股票列表
    filteredStockList() {
      if (this.showCurrentOnly) {
        // 获取当前持仓的股票代码列表
        const currentStockCodes = this.currentStocks.map(stock => stock.stockCode);
        return this.stockList.filter(stock => currentStockCodes.includes(stock.stockCode));
      }
      return this.stockList;
    },
    
    // 过滤后的股票数据
    filteredStockData() {
      if (this.showCurrentOnly) {
        // 获取当前持仓的股票代码列表
        const currentStockCodes = this.currentStocks.map(stock => stock.stockCode);
        return this.allStockData.filter(stock => currentStockCodes.includes(stock.stockCode));
      }
      return this.allStockData;
    },
    
    detailedData() {
      return this.filteredStockData.map(stock => {
        const returnRate = stock.breakEvenPrice > 0 
          ? ((stock.currentPrice - stock.breakEvenPrice) / stock.breakEvenPrice) * 100
          : 0
        
        const tProfitRatio = stock.profitLoss !== 0 
          ? parseFloat((Math.abs(stock.tProfit) / Math.abs(stock.profitLoss)) * 100).toFixed(1)
          : 0

        return {
          ...stock,
          returnRate,
          tProfitRatio,
          diff: Math.round((stock.currentPrice - stock.breakEvenPrice) * 1000* 100) / 100
        }
      })
    },

    // 排序后的数据
    sortedData() {
      if (!this.sortColumn) {
        return this.detailedData
      }

      return [...this.detailedData].sort((a, b) => {
        let valueA = a[this.sortColumn]
        let valueB = b[this.sortColumn]

        // 处理数值类型
        if (typeof valueA === 'number' && typeof valueB === 'number') {
          return this.sortOrder === 'ascending' ? valueA - valueB : valueB - valueA
        }

        // 处理字符串类型
        if (typeof valueA === 'string' && typeof valueB === 'string') {
          return this.sortOrder === 'ascending' 
            ? valueA.localeCompare(valueB) 
            : valueB.localeCompare(valueA)
        }

        return 0
      })
    },

    // 分页后的表格数据
    pagedTableData() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      return this.sortedData.slice(start, end)
    },
    
    pieChartData() {
      const data = this.filteredStockData
        .filter(stock => stock.profitLoss !== 0)
        .map(stock => ({
          name: `${stock.stockName}(${stock.stockCode})`,
          value: stock.profitLoss
        }))
        .sort((a, b) => Math.abs(b.value) - Math.abs(a.value))
        .slice(0, 20)
        
      console.log('饼状图数据:', data);
      return data;
    },
    
    hasChartData() {
      return this.pieChartData && this.pieChartData.length > 0;
    }
  },
  async mounted() {
    await this.loadAllData();
  },
  beforeUnmount() {
    if (this.chart) {
      this.chart.dispose();
    }
  },
  methods: {
    async loadAllData() {
      this.loading = true;
      try {
        const stockResponse = await getStockList();
        this.currentStocks = (await getCurrentStocks()).data;
        console.log('股票列表:', stockResponse);
        
        if (stockResponse.code === 200) {
          this.stockList = stockResponse.data || [];
          await this.loadAllStockData();
          
          this.$nextTick(() => {
            setTimeout(() => {
              this.initPieChart();
            }, 100);
          });
        }
      } catch (error) {
        console.error('加载数据失败:', error);
        this.$message.error('加载数据失败');
      } finally {
        this.loading = false;
      }
    },
    
    async loadAllStockData() {
      const promises = this.stockList.map(async (stock) => {
        try {
          const [latestData, tProfitData] = await Promise.all([
            getStockLatestData(stock.stockCode),
            getTotalTProfitByStockCode(stock.stockCode)
          ]);
          
          let stockData = {
            stockName: stock.stockName,
            stockCode: stock.stockCode,
            profitLoss: 0,
            currentPrice: 0,
            breakEvenPrice: 0,
            totalShares: 0,
            tProfit: 0,
            returnRate: 0
          };
          
          if (latestData.code === 200 && latestData.data) {
            stockData = {
              ...stockData,
              ...latestData.data,
              profitLoss: latestData.data.profitLoss || 0,
              currentPrice: latestData.data.currentPrice || 0,
              breakEvenPrice: latestData.data.breakEvenPrice || 0,
              totalShares: latestData.data.totalShares || 0
            };
          }
          
          if (tProfitData.code === 200) {
            stockData.tProfit = tProfitData.data || 0;
          }
          
          return stockData;
        } catch (error) {
          console.error(`加载股票 ${stock.stockCode} 数据失败:`, error);
          return {
            stockName: stock.stockName,
            stockCode: stock.stockCode,
            profitLoss: 0,
            currentPrice: 0,
            breakEvenPrice: 0,
            totalShares: 0,
            tProfit: 0,
            returnRate: 0
          };
        }
      });
      
      this.allStockData = await Promise.all(promises);
      console.log('所有股票数据:', this.allStockData);
      this.calculateSummary();
      this.allDataLoaded = true;
    },
    
    calculateSummary() {
      const targetData = this.showCurrentOnly ? 
        (() => {
          const currentStockCodes = this.currentStocks.map(stock => stock.stockCode);
          return this.allStockData.filter(stock => currentStockCodes.includes(stock.stockCode));
        })() : 
        this.allStockData;
      
      if (!targetData.length) return;
      
      this.totalProfit = targetData.reduce((sum, stock) => sum + (stock.profitLoss || 0), 0);
      this.totalTProfit = targetData.reduce((sum, stock) => sum + (stock.tProfit || 0), 0);
      
      const validReturns = targetData.filter(stock => stock.breakEvenPrice > 0);
      if (validReturns.length > 0) {
        this.averageReturnRate = validReturns.reduce((sum, stock) => {
          const returnRate = ((stock.currentPrice - stock.breakEvenPrice) / stock.breakEvenPrice) * 100;
          return sum + returnRate;
        }, 0) / validReturns.length;
      }
    },
    
    handleFilterChange() {
      this.currentPage = 1;
      this.calculateSummary();
      this.$nextTick(() => {
        this.initPieChart();
      });
    },
    
    // 排序处理
    handleSortChange({ prop, order }) {
      this.sortColumn = prop
      this.sortOrder = order
      this.currentPage = 1 // 排序后重置到第一页
    },
    
    // 分页切换事件
    handlePageChange(page) {
      this.currentPage = page;
    },
    
    initPieChart() {
      if (!this.$refs.pieChart) {
        console.error('图表容器未找到');
        return;
      }
      
      if (!this.hasChartData) {
        console.log('没有图表数据');
        return;
      }
      
      try {
        this.chart = echarts.init(this.$refs.pieChart);
        
        // 定义更多颜色
        const colors = [
          '#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de',
          '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc', '#ff9f7f',
          '#ff7b7b', '#7b68ee', '#00ced1', '#ff6347', '#4682b4',
          '#32cd32', '#ff69b4', '#8a2be2', '#ff4500', '#20b2aa'
        ];
        
        const option = {
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: ¥{c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            right: 100,
            top: 'center',
            type: 'scroll',
            textStyle: {
              fontSize: 14  // 增大文字大小
            },
            itemWidth: 14,  // 增大项目宽度
            itemHeight: 14,  // 增大项目高度
            pageButtonItemGap: 5,
            pageFormatter: '{current}/{total}',
            pageIconSize: 12,
            pageTextStyle: {
              fontSize: 12
            },
            selector: true,
            selectorPosition: 'end'
          },
          color: colors,
          series: [
            {
              name: '股票收益',
              type: 'pie',
              radius: ['15%', '55%'],  // 调整饼图大小
              center: ['30%', '50%'],  // 调整中心位置，为图例腾出更多空间
              data: this.pieChartData,
              label: {
                show: true,
                position: 'outside',
                formatter: '{d}%',
                fontSize: 12,  // 增大标签文字大小
                fontWeight: 'bold'
              },
              labelLine: {
                show: true,
                length: 8,  // 增长标签线
                length2: 12
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: 14,  // 增大强调时文字大小
                  fontWeight: 'bold'
                }
              },
              itemStyle: {
                borderRadius: 4,
                borderColor: '#fff',
                borderWidth: 2
              },
              minAngle: 2,  // 最小角度，防止过小的扇形
              avoidLabelOverlap: true  // 避免标签重叠
            }
          ]
        };
        
        this.chart.setOption(option);
        console.log('图表已初始化并设置数据');
        
        // 响应式调整
        window.addEventListener('resize', () => {
          if (this.chart) {
            this.chart.resize();
          }
        });
        
      } catch (error) {
        console.error('图表初始化失败:', error);
      }
    },
    
    formatNumber(value) {
      if (value === null || value === undefined) return '0.00';
      return parseFloat(value).toFixed(2);
    },
    
    getProfitClass(value) {
      if (value > 0) return 'profit-positive';
      if (value < 0) return 'profit-negative';
      return 'profit-zero';
    }
  }
}
</script>

<style scoped>
.all-profit-statistics {
  padding: 10px;
  max-width: 800px;
  margin: 0 auto;
}

.box-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-title i {
  color: #E6A23C;
}

.summary-info {
  font-size: 12px;
  color: #909399;
  font-weight: normal;
}

.overall-summary {
  margin-bottom: 15px;
}

.summary-card {
  text-align: center;
  padding: 12px 8px;
  background: #f8f9fa;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.summary-card:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.summary-card.highlight {
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7ed 100%);
}

.summary-title {
  font-size: 12px;
  color: #606266;
  margin-bottom: 6px;
  font-weight: 500;
}

.summary-value {
  font-size: 18px;
  font-weight: bold;
}

.section-title {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 10px;
  text-align: center;
}

/* 紧凑布局样式 */
.compact {
  margin: 5px 0;
}

.compact-title {
  margin-bottom: 8px;
  font-size: 14px;
}

.echarts-container {
  width: 100%;
  height: 300px;
}

.compact-chart {
  height: 280px;
  margin: 5px 0;
}

.no-chart-data {
  padding: 20px 0;
  text-align: center;
}

.compact-empty {
  padding: 15px 0;
}

.detailed-table {
  margin-top: 15px;
}

/* 分页样式 */
.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: center;
  padding: 10px 0;
}

/* 排序样式 */
:deep(.el-table .sort-caret.ascending) {
  border-bottom-color: #409eff;
}

:deep(.el-table .sort-caret.descending) {
  border-top-color: #409eff;
}

.profit-positive {
  color: #F56C6C;
}

.profit-negative {
  color: #67C23A;
}

.profit-zero {
  color: #909399;
}

.loading {
  padding: 30px 0;
  text-align: center;
}

.empty {
  padding: 30px 0;
  text-align: center;
}

@media (max-width: 768px) {
  .echarts-container {
    height: 250px;
  }
  
  .compact-chart {
    height: 220px;
  }
  
  .overall-summary .el-col {
    margin-bottom: 8px;
  }
}
</style>